package com.jia.lidao.ui;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Proxy;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.jia.lidao.R;
import com.jia.lidao.RunningContext;
import com.jia.lidao.UserUtils;
import com.jia.lidao.enity.BaseResponseDTO;
import com.jia.lidao.enity.ShareInformation;
import com.jia.lidao.others.API;
import com.jia.lidao.others.UserInfoUtil;
import com.jia.lidao.others.enity.ObjectCallBack;
import com.jia.lidao.others.enity.Province;
import com.jia.lidao.others.enity.QuickOrder;
import com.jia.lidao.others.ui.BasicMapActivity;
import com.jia.lidao.others.ui.EditOrderFormActivity;
import com.jia.lidao.others.ui.ShoppingCartActivity;
import com.jia.lidao.others.utils.GsonUtils;
import com.jia.lidao.utils.LogUtil;
import com.jia.lidao.utils.WXEntryUtil;
import com.lidroid.xutils.view.annotation.event.OnProgressChanged;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.unionpay.mobile.android.utils.r;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import okhttp3.Call;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static com.jia.lidao.Constans.QQ_APP_ID;
import static com.jia.lidao.others.ui.fragment.EditOrderFormFragment.KEY_QUICK_ORDER;


/**
 * webview界面
 * <p>
 * Created by czhang on 16/7/8.
 */
public class WebActivity extends BaseActivity implements IUiListener {
    //http://192.168.43.15:8010/#/

    private final static String H5_SERVER_URL = "http://h5.agent.ldnz.rxjt.co/#/";
    //private final static String H5_SERVER_URL = "http://192.168.100.119:8010/#/";

    public static final String INTENT_EXTRA_BEGIN_URL = "beginUrl";
    private String token;

    private Tencent mTencent;


    private ShareInformation shareInformation;
    private Bitmap wxBitmap;
    private String address_params = "";

    private static final int GAODI_ADDRESS = 0x15;


    WebView mWebView;
    private String url;
    private String param;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    break;
                case 1:
                    break;
                case 2:
                    break;
                default:
                    break;
            }
        }

        ;
    };


    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;


    private static final int GET_ADDRESS = 0x12;
    private static final int SHIPPING_ADDRESS = 0x13;
    private boolean isLoadUrl = false;
    private RelativeLayout loadingRl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rp_activity_web);
        token = UserUtils.getInstance().getAuthor().access_token;
        mTencent = Tencent.createInstance(QQ_APP_ID, getApplicationContext());
        param = getIntent().getStringExtra(INTENT_EXTRA_BEGIN_URL);
        if (param.contains("?")) {
            url = H5_SERVER_URL + param + "&token=" + token + "&source=app";
        } else {
            url = H5_SERVER_URL + param + "?token=" + token + "&source=app";
        }
        if(!url.contains("latitude")){
            url+="&latitude="+RunningContext.mLatitude+"&longitude="+RunningContext.mLongitude;
        }
        Log.e("HQQ", "url: " + url);
        mWebView = (WebView) findViewById(R.id.webView);
        loadingRl = (RelativeLayout) findViewById(R.id.loadingview);
        initData();
    }

    @SuppressLint("JavascriptInterface")
    public void initData() {
        mWebView.setHorizontalScrollBarEnabled(false);//水平不显示
        mWebView.setVerticalScrollBarEnabled(false); //垂直不显s
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        //支持缩放
        webSettings.setSupportZoom(false);
        //设置缓存模式
    /*    webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);//开启DOM缓存
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setAppCachePath(mWebView.getContext().getCacheDir().getAbsolutePath());*/
        //支持插件
        webSettings.setPluginState(WebSettings.PluginState.ON);
        //设置适应屏幕
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //隐藏原生的缩放控件
        webSettings.setDisplayZoomControls(false);
        //支持内容重新布局
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.supportMultipleWindows();
        webSettings.setSupportMultipleWindows(true);

        //设置可访问文件
        webSettings.setAllowFileAccess(true);
        //当webview调用requestFocus时为webview设置节点
        webSettings.setNeedInitialFocus(true);
        //支持自动加载图片
        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setLoadsImagesAutomatically(true);
        } else {
            webSettings.setLoadsImagesAutomatically(false);
        }
        webSettings.setNeedInitialFocus(true);
        //设置编码格式
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();

        webSettings.setAppCachePath(appCachePath);

        webSettings.setAllowFileAccess(true);

        webSettings.setAppCacheEnabled(true);


      /*  ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if( null != networkInfo && networkInfo.isAvailable()) {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//网络正常时使用默认缓存策略
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);//网络不可用时只使用缓存
        }*/

        mWebView.loadUrl(url);
        mWebView.setWebChromeClient(new GoldWebChromeClient());
        mWebView.setWebViewClient(new GoldWebViewClient());
        mWebView.addJavascriptInterface(new JsObject(), "myObject");
        shareInformation();
    }


    private void shareInformation() {
        String url = API.INVITATION + "&access_token=" + token;
        HashMap<String, String> header = new HashMap<>();
        header.put("Accept", "*/*");
        LogUtil.printJ("url=" + url);

        TypeToken<ShareInformation> typeToken = new TypeToken<ShareInformation>() {
        };
        OkHttpUtils.get().headers(header).url(url).build().execute(new ObjectCallBack<ShareInformation>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ShareInformation response, int id) {
                if (response.getErr_code() == 0) {
                    shareInformation = response;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                wxBitmap = Glide.with(getApplicationContext())
                                        .load(shareInformation.getShare().getIcon())
                                        .asBitmap() //必须
                                        .into(50, 50)
                                        .get();
                                if (wxBitmap == null) {
                                    wxBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.wxlogo);
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } catch (ExecutionException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                }

            }
        });
    }


    @Override
    public void onComplete(Object o) {
        showToast("分享成功");
    }

    @Override
    public void onError(UiError uiError) {
        showToast("分享失败");
    }

    @Override
    public void onCancel() {
        showToast("分享取消");
    }

//    public void onViewClicked() {
//
//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.nongzi);
//        WXEntryUtil.ShareCaseWebPageToWeixin(getApplicationContext(), bitmap, "粒到农资", "粒到农资", url);
//    }


    /***
     * webChromeClient主要是将javascript中相应的方法翻译成android本地方法
     * <p/>
     * 例如：我们重写了onJsAlert方法，那么当页面中需要弹出alert窗口时，便
     * 会执行我们的代码，按照我们的Toast的形式提示用户。
     */
    class GoldWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress == 100) {
                //mProgress.setVisibility(View.GONE);
                loadingRl.setVisibility(View.GONE);
                //mProgressBar.setVisibility(View.GONE);
            } else {
                /*if(!mProgress.isShown()){
                    mProgress.setVisibility(View.VISIBLE);
                }
                mProgress.setProgress(newProgress);*/
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            uploadMessageAboveL = filePathCallback;
            openImageChooserActivity();
            return true;
        }


    }


    class GoldWebViewClient extends WebViewClient {

        /*点击页面的某条链接进行跳转的话，会启动系统的默认浏览器进行加载，调出了我们本身的应用
         * 因此，要在shouldOverrideUrlLoading方法中
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            //使用当前的WebView加载页面
            Log.e("HQQ", "url  888  : " + url);
            String[] urlstartsWith = url.split("://");
            String urlStart = urlstartsWith[0];

            if (!urlStart.startsWith("http")) { //私有协议非 HTTP  或者HTTPs
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);   //当协议不是https或者http时就创建一个Intent用来打开对应的客户端app，如果你的手机上没有对应的客户端，第三方的自定义协议就会提供网页版的
                } catch (ActivityNotFoundException e) { //（不过如果没安装的话会报错，代码try catch，是为了保证程序不会崩溃

                }
            } else if (url.contains(".apk")) {
                Intent intent = new Intent();
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                startActivity(intent);
            } else {
                view.loadUrl(url);
            }

            return true;
        }


        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            Log.e("HQQ", " onReceivedError");
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (!isLoadUrl) {
                isLoadUrl = true;
                view.loadUrl(url);
            }
            loadingRl.setVisibility(View.VISIBLE);
            super.onPageStarted(view, url, favicon);
            Log.e("HQQ", "onPageStarted url: " + url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    }


    private void openImageChooserActivity() {
//        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//        i.addCategory(Intent.CATEGORY_OPENABLE);
//        i.setType("image/*");
//        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, FILE_CHOOSER_RESULT_CODE);
    }


    class JsObject {
        //
//        @JavascriptInterface
//        public void selectLotteryAddress() {  //选择收货地址
//            Intent intent = new Intent(getApplicationContext(), AddressActivity.class);
//            startActivityForResult(intent, SHIPPING_ADDRESS);
//
//        }
//
        @JavascriptInterface
        public void gotoMap(String param) {  ///进入地图显示店铺
            Log.e("HQQ", " param : " + param);
            Intent intent = new Intent(getApplicationContext(), BasicMapActivity.class);
            intent.putExtra("param", param);
            startActivityForResult(intent, GAODI_ADDRESS);
        }

        @JavascriptInterface
        public void createBill(String prodInfo) {  //立即购买
            Log.e("HQQ", "prodInfo: " + prodInfo);
            try {
                TypeToken<QuickOrder> typeToken = new TypeToken<QuickOrder>() {
                };
                QuickOrder result = GsonUtils.fromJson(prodInfo, typeToken);
                Intent intent = new Intent(WebActivity.this, EditOrderFormActivity.class);
                intent.putExtra(KEY_QUICK_ORDER, prodInfo);
                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @JavascriptInterface
        public void getCoupon(String coupon) {   //获取优惠券
            Intent intent = new Intent();
            intent.putExtra("coupon", coupon);
            setResult(Activity.RESULT_OK, intent);
            finish();
        }

        //
        @JavascriptInterface
        public void gotoShopCart() {  //进入购物车
            Intent intent = new Intent(getApplicationContext(), ShoppingCartActivity.class);
            startActivity(intent);
        }

        //
//        @JavascriptInterface
//        public void selectAddress() { ////推广商选择省市区
//            Intent intent = new Intent(getApplicationContext(), CityListActivity.class);
//            startActivityForResult(intent, GET_ADDRESS);
//        }
//
        @JavascriptInterface
        public void shareQQ() {   /////分享qq
            Log.e("HQQ", "shareQQ ");
            if (null != shareInformation) {
                shareToQQ();
            }

        }

        @JavascriptInterface
        public void shareSpace() { ///分享空间
            Log.e("HQQ", "shareSpace ");
            if (null != shareInformation) {
                shareToQZone();
            }
        }


        @JavascriptInterface
        public void shareWX() {  /////分享微信
            Log.e("HQQ", "shareWX " + shareInformation.getShare().getIcon());
            if (null != shareInformation) {
                WXEntryUtil.ShareCaseWebPageToWeixin(getApplicationContext(), wxBitmap, shareInformation.getShare().getTitle(), shareInformation.getShare().getDesc(), shareInformation.getShare().getLink());
            }
        }

        @JavascriptInterface
        public void shareFriends() { ///分享朋友圈
            WXEntryUtil.ShareCaseWebPageToWeixinFriendGroup(getApplicationContext(), wxBitmap, shareInformation.getShare().getTitle(), shareInformation.getShare().getDesc(), shareInformation.getShare().getLink());
        }


        @JavascriptInterface
        public void callPhone(String phonenum) {
            LogUtil.printJ("phonenum=" + phonenum);
            try {
                JSONObject object = new JSONObject(phonenum);
                String phone = object.optString("phone");
                Uri uri = Uri.parse("tel:" + phone);
                Intent intent = new Intent(Intent.ACTION_CALL, uri);
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
//            {
//                Uri uri = Uri.parse("tel:" + phonenum);
//                Intent intent = new Intent(Intent.ACTION_CALL, uri);
//                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
//            }
        }

        //
//        @JavascriptInterface
//        public void gotoMap() {  ///进入地图显示店铺
//            Intent intent = new Intent(getApplicationContext(), BasicMapActivity.class);
//            startActivity(intent);
//        }
//
        @JavascriptInterface
        public void gotoLogin(){
            UserInfoUtil.intoLogin(WebActivity.this);
        }

        @JavascriptInterface
        public void createBill() {
            Intent intent = new Intent(getApplicationContext(), EditOrderFormActivity.class);
            startActivity(intent);
        }

        //
        @JavascriptInterface
        public void backApp() {
            finish();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case GET_ADDRESS:
                Province.RegionsBean myProvince = (Province.RegionsBean) data.getSerializableExtra("Province");
                Province.RegionsBean myCity = (Province.RegionsBean) data.getSerializableExtra("City");
                Province.RegionsBean myArea = (Province.RegionsBean) data.getSerializableExtra("Area");
                url = url + "&provinceName=" + myProvince.getName() +
                        "&provinceId=" + myProvince.getId()
                        + "&cityName=" + myCity.getName()
                        + "&cityId=" + myCity.getId()
                        + "&countyName=" + myArea.getName()
                        + "&countyId=" + myArea.getId();
                mWebView.loadUrl(url);
                Log.e("HQQ", "urlurl : " + url);
                break;
//            case SHIPPING_ADDRESS:
//                Address.AddressesBean.DataBean dataBean = (Address.AddressesBean.DataBean) data.getSerializableExtra("Address");
//                Log.e("HQQ", " Address : " + dataBean.getCounty_id());
//                break;
            case FILE_CHOOSER_RESULT_CODE:
                if (null == uploadMessage && null == uploadMessageAboveL)
                    return;
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                if (uploadMessageAboveL != null) {
                    onActivityResultAboveL(requestCode, resultCode, data);
                } else if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(result);
                    uploadMessage = null;
                }
                break;
            case Constants.REQUEST_API: //QQ分享
                Tencent.onActivityResultData(requestCode, resultCode, data, this);
                if (resultCode == Constants.REQUEST_QQ_SHARE || resultCode == Constants.REQUEST_QZONE_SHARE || resultCode == Constants.REQUEST_OLD_SHARE) {
                    Tencent.handleResultData(data, this);
                }
                break;
            case GAODI_ADDRESS:
                mWebView.reload();
                break;
        }
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }


    private Bundle params;

    private void shareToQQ() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                params = new Bundle();
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, shareInformation.getShare().getTitle());// 标题
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareInformation.getShare().getDesc());// 摘要
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareInformation.getShare().getLink());// 内容地址

                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, shareInformation.getShare().getIcon());// 网络图片地址　　
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, getResources().getString(R.string.app_name));// 应用名称
                params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "其它附加功能");
// 分享操作要在主线程中完成
                mTencent.shareToQQ(WebActivity.this, params, WebActivity.this);
            }
        });

    }


    private void shareToQZone() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                params = new Bundle();
                params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
                params.putString(QzoneShare.SHARE_TO_QQ_TITLE, shareInformation.getShare().getTitle());// 标题
                params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, shareInformation.getShare().getDesc());// 摘要
                params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, shareInformation.getShare().getLink());// 内容地址
                ArrayList<String> imgUrlList = new ArrayList<>();
                imgUrlList.add(shareInformation.getShare().getIcon());
                params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imgUrlList);// 图片地址
// 分享操作要在主线程中完成
                mTencent.shareToQzone(WebActivity.this, params, WebActivity.this);
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (mWebView != null && mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }

}
